package com.cardmanager.pro.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.cardmanager.pro.repository.RepaymentTaskPOJORepository;
import com.cardmanager.pro.util.CommonsUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cardmanager.pro.authorization.CreditCardManagerAuthorizationHandle;
import com.cardmanager.pro.business.ConsumeTaskPOJOBusiness;
import com.cardmanager.pro.business.RepaymentTaskPOJOBusiness;
import com.cardmanager.pro.pojo.ConsumeTaskPOJO;
import com.cardmanager.pro.pojo.RepaymentTaskPOJO;
import com.cardmanager.pro.util.RestTemplateUtil;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;

/**
 * 还款计划表
 * @author chengyingli
 */
@Controller
@EnableAutoConfiguration
public class TaskBillService {
	private final Logger LOG = LoggerFactory.getLogger(getClass());


	private RestTemplateUtil util;

	private final RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness;
	private final ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness;
	private final CreditCardManagerAuthorizationHandle creditCardManagerAuthorizationHandle;
	private final RepaymentTaskPOJORepository repaymentTaskPOJORepository;

	@Autowired
	public TaskBillService(CreditCardManagerAuthorizationHandle creditCardManagerAuthorizationHandle,
						   ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness,
						   RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness,
						   RepaymentTaskPOJORepository repaymentTaskPOJORepository) {
		this.creditCardManagerAuthorizationHandle = creditCardManagerAuthorizationHandle;
		this.consumeTaskPOJOBusiness = consumeTaskPOJOBusiness;
		this.repaymentTaskPOJOBusiness = repaymentTaskPOJOBusiness;
		this.repaymentTaskPOJORepository = repaymentTaskPOJORepository;
	}

	@RequestMapping(value = "/v1.0/creditcardmanager/query/taskbill/all/batchno")
	public @ResponseBody Object queryList(@RequestParam(value = "userId") String userId,
							@RequestParam(value = "orderNo",required = false) String orderNo,
							@RequestParam(value = "creditCardNumber",required = false) String creditCardNumber,
							@RequestParam(value = "status",required = false) String status,
							@RequestParam(value = "type",required = false) String type,
							@RequestParam(value = "page", defaultValue = "0", required = false) int page,
							@RequestParam(value = "size", defaultValue = "20", required = false) int size,
							@RequestParam(value = "order", defaultValue = "DESC", required = false) Sort.Direction direction,
							@RequestParam(value = "sort", defaultValue = "createTime", required = false) String sortProperty) {
		Pageable pageable = new PageRequest(page, size, new Sort(direction, sortProperty));

		try {
			if (StringUtils.isBlank(userId)) {
				return CommonsUtil.returnError("用户id不能为空");
			}
			Map<String,Object> map = repaymentTaskPOJOBusiness.findRepaymentList( userId, creditCardNumber, status, type, orderNo,pageable);
			return map;
		} catch (Exception e) {
			return CommonsUtil.returnError("查询代还失败");
		}
	}


	/**
	 * 根据创建时间获取项目计划
	 * @param userId
	 * @param creditCardNumber
	 * @param createTime
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/query/taskbill/by/createtime")
	public @ResponseBody Object ggetRepaymentTaskByCreateTime( @RequestParam(value = "userId") String userId,
															  @RequestParam(value = "creditCardNumber") String creditCardNumber,
															  @RequestParam(value = "createTime") String createTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> verifyStringFiledIsNullMap = creditCardManagerAuthorizationHandle
				.verifyStringFiledIsNull(userId, creditCardNumber, createTime);
		if (!CommonConstants.SUCCESS.equals(verifyStringFiledIsNullMap.get(CommonConstants.RESP_CODE))) {
			return verifyStringFiledIsNullMap;
		}

		createTime = createTime + ".0";
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByCreateTime(userId,
				creditCardNumber, createTime);

		if (!repaymentTaskPOJOs.isEmpty() && repaymentTaskPOJOs.size() > 0) {
			for (RepaymentTaskPOJO repaymentTaskPOJO : repaymentTaskPOJOs) {
				repaymentTaskPOJO = processingData(repaymentTaskPOJO);
			}
		}
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, repaymentTaskPOJOs);
		return map;
	}

	/**
	 * 查询用户当前信用卡总消费金额和总还款金额
	 * @param userId
	 * @param creditCardNumber
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/find/allamount/by/userid")
	public @ResponseBody Object queryRepaymentTask(@RequestParam(value="userId")String userId,
												   @RequestParam(value = "creditCardNumber") String creditCardNumber) {
		Map<String, Object> map = new HashMap<>();
		List<Object[]> result = repaymentTaskPOJOBusiness.queryRepaymentTaskAllamountByUserIdAndCardno(userId,creditCardNumber);

		map.put("consumeAmount", result.size()>0 ? result.get(0)[1] : "0");
		map.put("repaymentAmount", result.size()>0 ? result.get(0)[0] : "0");
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功!");
		return map;

	}

	private <T> T processingData(T source) {
		Date nowTime = new Date();
		if (source instanceof RepaymentTaskPOJO) {
			RepaymentTaskPOJO model = (RepaymentTaskPOJO) source;
			int status = model.getTaskStatus();
			String executeDate = model.getExecuteDate();
			String nowDate = DateUtil.getDateStringConvert(new String(), nowTime, "yyyy-MM-dd");
			if (status == 0) {
				if (nowDate.equals(executeDate)) {
					model.setTaskStatus(3);
				} else {
					model.setTaskStatus(2);
				}
			} else if (status == 1) {
				model.setTaskStatus(1);
			} else if (status == 2) {
				model.setTaskStatus(4);
			}
			return (T) model;
		} else if (source instanceof ConsumeTaskPOJO) {
			ConsumeTaskPOJO model = (ConsumeTaskPOJO) source;
			int status = model.getTaskStatus();
			String executeDate = model.getExecuteDate();
			String nowDate = DateUtil.getDateStringConvert(new String(), nowTime, "yyyy-MM-dd");
			if (status == 0) {
				if (nowDate.equals(executeDate)) {
					model.setTaskStatus(3);
				} else {
					model.setTaskStatus(2);
				}
			} else if (status == 1) {
				model.setTaskStatus(1);
			} else if (status == 2) {
				model.setTaskStatus(4);
			}
			return (T) model;
		}
		return source;
	}

	/**
	 * 获取还款计划详细划分类别
	 * @param repaymentTaskId
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/query/consumetask/by/repaymenttaskid")
	public @ResponseBody Object getTaskStatus0RepaymentTask(@RequestParam(value = "repaymentTaskId") String repaymentTaskId) {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> verifyStringFiledIsNullMap = creditCardManagerAuthorizationHandle
				.verifyStringFiledIsNull(repaymentTaskId);
		if (!CommonConstants.SUCCESS.equals(verifyStringFiledIsNullMap.get(CommonConstants.RESP_CODE))) {
			return verifyStringFiledIsNullMap;
		}
		List tasks = consumeTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskId);
		ConsumeTaskPOJO model = null;
		Date nowTime = new Date();
		if (tasks != null && tasks.size() > 0) {
			for (Object obj : tasks) {
				model = (ConsumeTaskPOJO) obj;
				model = processingData(model);
				model.setTaskType(0);
			}
		}

		RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskId);
		if (repaymentTaskPOJO != null) {
			repaymentTaskPOJO = processingData(repaymentTaskPOJO);
			repaymentTaskPOJO.setTaskType(1);
		}
		tasks.add(repaymentTaskPOJO);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "查询成功");
		map.put(CommonConstants.RESULT, tasks);
		return map;
	}

	/**
	 * 删除还款计划
	 * @param repaymentTaskId
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/delete/repaymenttask/by/repaymenttaskid")
	public @ResponseBody Object deleteRepaymentTaskByTaskStatus7(@RequestParam(value="repaymentTaskId")String repaymentTaskId){
		Map<String,Object>map = new HashMap<>();
		Map<String, Object> verifyStringFiledIsNullMap = creditCardManagerAuthorizationHandle.verifyStringFiledIsNull(repaymentTaskId);
		if(!CommonConstants.SUCCESS.equals(verifyStringFiledIsNullMap.get(CommonConstants.RESP_CODE))){
			return verifyStringFiledIsNullMap;
		}
		
		RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskId);
		
		if(repaymentTaskPOJO==null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "您要删除的任务不存在!");
			return map;
		}
		
		Date nowDate = new Date();
		nowDate = DateUtil.getDateStringConvert(new Date(), nowDate, "yyyy-MM-dd");
		Date executeDate = DateUtil.getDateStringConvert(new Date(), repaymentTaskPOJO.getExecuteDate(), "yyyy-MM-dd");
		if(nowDate.getTime() >= executeDate.getTime()){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "删除失败,只能删除今天以后的任务,当天任务及已执行的任务无法删除,当天还款任务将在23点之前进行出款!");
			return map;
		}
		
		repaymentTaskPOJO.setTaskStatus(7);
		repaymentTaskPOJO.setDescription(repaymentTaskPOJO.getDescription()+"|用户已删除");
		
		List<ConsumeTaskPOJO> consumeTaskPOJOs = consumeTaskPOJOBusiness.findByRepaymentTaskId(repaymentTaskId);
		for(ConsumeTaskPOJO consumeTaskPOJO:consumeTaskPOJOs){
			consumeTaskPOJO.setTaskStatus(7);
			consumeTaskPOJO.setDescription(consumeTaskPOJO.getDescription()+"|用户已删除");
		}
		consumeTaskPOJOBusiness.deleteRepaymentTaskAndConsumeTask(repaymentTaskPOJO,consumeTaskPOJOs);
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "删除成功!");
		return map;
	}



}
